#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int udp_init(int port)
{
    int sock = 0;

    struct timeval tv_out;
    struct sockaddr_in addr;
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
        return -1;

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(port);
    if (bind(sock,(struct sockaddr *)&addr,sizeof(addr))<0)
    {
        close(sock);
        return -1;
    }

    tv_out.tv_sec = 3;
    tv_out.tv_usec = 0;
    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv_out, sizeof(tv_out));

    return sock;
}


int udp_send(int sock, const char *ip,int port,const void *msg,unsigned int len)
{
    if (ip == NULL || port == 0 || msg == NULL)
        return -1;

    unsigned int addrlen = sizeof(struct sockaddr_in);
    struct sockaddr_in addr;
    memset(&addr, 0x0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(port);

    return	sendto(sock,msg,len,0,(struct sockaddr *)&addr,addrlen);
}
int udp_recv(int sock,void *msg, unsigned int len)
{
    int n = 0;
    unsigned int addrlen = sizeof(struct sockaddr_in);
    struct sockaddr_in addr;
    memset(&addr, 0x0, sizeof(addr));
    memset(msg,0x0,sizeof(msg));

    n = recvfrom(sock, (void *)msg, len, 0, (struct sockaddr *)&addr, &addrlen);
    if (n < 0 ) {
        if (errno == EAGAIN  ||errno == EINTR)
            return 0;
    }
    return n;

}


void udp_destroy(int sock)
{
    close(sock);
}
